package app.ui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

import app.action.AppUtilities;

public class MainFrame extends AbsMainFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8924308466844158184L;

	protected GridBagConstraints constraints;

	protected AppUtilities appUtilities;
	protected StartScr startScr;
	protected WorkScr workScr;

	public MainFrame(AppUtilities appUtilities) {
		super(appUtilities);

		this.appUtilities = appUtilities;
		this.getContentPane().setLayout(new GridBagLayout());
		this.addWindowListener(new WindowAction());
		this.constraints = new GridBagConstraints();
		constraints.fill = GridBagConstraints.BOTH;
		constraints.weightx = 1;
		constraints.weighty = 1;

		setDefaultCloseOperation(EXIT_ON_CLOSE);
		initialize();
	}

	/**
	 * Commonly add components here
	 */
	public void initialize() {
		Dimension size = new Dimension(800, 600);
		setSize(size);
		setMinimumSize(size);
		setLocation(280, 120);

		// construction
		this.workScr = new WorkScr(this);
		this.startScr = new StartScr(this);
		// add components
		startScr.open();
	}

	@Override
	public Component add(Component comp) {
		if(comp instanceof AbsCommonPanel) {
			AbsCommonPanel mPanel = (AbsCommonPanel) comp;
			mPanel.makeThisAutoResize();
			this.getContentPane().add(comp, getConstraints());
			return comp;
		}

		return super.add(comp);
	}

	public GridBagConstraints getConstraints() {
		return constraints;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public StartScr getStartScr() {
		return startScr;
	}

	public WorkScr getWorkScr() {
		return workScr;
	}

	public AppUtilities getAppUtilities() {
		return appUtilities;
	}

	public void savingStatusBeforClosing() {
		try {
			System.out.println("Application is closed!");
			appUtilities.storingPropertiesFile();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void closing() {
		this.savingStatusBeforClosing();
		System.exit(0);
	}
}

class WindowAction extends WindowAdapter {

	@Override
	public void windowClosing(WindowEvent e) {
		MainFrame mFrame = (MainFrame) e.getSource();
		mFrame.savingStatusBeforClosing();
		super.windowClosing(e);
	}

}
